<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  users
 */

class m_users_actions_block_front_LoginAction extends f_core_Action
{
    private $user;
    private $groups;
    private $cookie;
    
	public function execute()
	{
        $pageId = $this->getBlockParameter("pageRedirect");
        $this->getAuthorizedGroups();

        $this->cookie = f_core_Cookie::getInstance()->setName("login")->setExpiration(time()+365*24*3600);
        $cookie = $this->cookie->getCookie();

        if(!is_null($cookie) && is_null($this->getUser()))
        {
            $this->logIn($cookie);
        }

        $user = $this->getUser();
        $access = $this->isAuthorized($user);

        if(!$access)
        {
            $errors = $this->logIn();
            $this->addToModel("errors", $errors);
        }
        else
        {
            $this->addToModel("user", $user);
        }

        $this->addToModel("blockParams", $this->getBlockContext()->getParameters());
        $this->addToModel("access", $access);
		$this->setView('success');
	}	
	
	public function validate()
	{
		return true;
	}
	
	public function errorHandler()
	{
		$this->setView('error');
	}
    
    private function logIn($cookie = false)
    {
        $key = m_backoffice_services_BackOfficeService::getKey();
        if(!$cookie)
        {
            $values = $this->getFormValues("FormLogin");
            if(!is_null($values))
            {
                $values["password"] = md5($values['password'].$key);
            }
        }
        else
        {
            $values = $cookie;
        }

		if(!is_null($values))
		{
			$errors = $this->checkLoginForm($values);

			if(count($errors) == 0)
			{
				$user = $this->user;

                if(isset($values["remember"]))
                {
                    $this->cookie->setCookie(array("login" => $user->getLogin(), "password" => $values["password"]));
                }

				$rights = m_rights_services_RightsService::getInstance()->getUserRights($user);
				$this->getUserContext()->removeRights()->setUser($user);

				foreach($rights as $right)
				{
					$this->getUserContext()->addRight($right);
				}

                $this->redirect();
			}

            return $errors;
		}

        return false;
    }

	/**
	 * Check login form
	 *
	 * @param $values
	 * @return array
	 */
	private function checkLoginForm($values)
	{
		$documentProvider = f_document_Provider::getInstance();
        $loginSys = $this->getBlockParameter("loginSys", "login");

		$user = $documentProvider->loadDocuments("modules_users/user")
                                        ->whereIsEqual($loginSys, $values['login'])
                                        ->whereIsEqual("password", $values['password'])
                                        ->byPublicationStatus("PUBLISHED")
                                        ->retrieveFirstDocument();

        $valid = $this->isAuthorized($user);

        if($valid == false)
        {
            $errors["errors"] = $this->getLocale("users.locales.badLogPass");
        }

		return $errors;
	}

   	private function redirect()
    {
        $pageIds = explode(",",$this->getBlockParameter("pageRedirect"));
        $url = URL_ABSOLUTE;

        if(is_array($pageIds) && is_numeric($this->groups))
        {
            $url = $this->getDocumentProvider()->getByUniqueId($pageIds[$this->groups], $this->getBlockParameter("pageLang"))->getUrl();
        }

        $this->getController()->redirect($url);
    }

    private function getAuthorizedGroups()
    {
        if(!is_null($this->getBlockParameter("group")))
        {
            $groups = explode(",",$this->getBlockParameter("group"));

            foreach($groups as $groupId)
            {
                $this->groups[] = $this->getDocumentProvider()->getByModelAndUniqueId("modules_users/group", $groupId, $this->getBlockParameter("pageLang"));
            }
        }
        else
        {
            $this->groups = array();
        }
    }

    private function isAuthorized($user)
    {
        $valid = false;
        
        if(!is_null($user) && is_object($user))
        {
            foreach($this->groups as $key => $group)
            {
                $valid = $user->belongsGroup($group);
                if($valid == true)
                {
                    $this->user = $user;
                    $this->groups = $key;
                    break;
                }
            }
        }

        return $valid;
    }
}